<template>
  <div
    ref="refChart"
    :class="className"
    :style="{ height: height, width: width, 'min-height': '120px' }"
  />
</template>

<script setup>
const props = defineProps({
  className: {
    type: String,
    default: 'nw-chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '28vh'
  },
  deviceActiveRate: {
    type: Object,
    default: () => {}
  },
  autoResize: {
    type: Boolean,
    default: true
  }
})

const refChart = ref(null)
const myChart = ref(null)
const dataOptions = ref([
  {
    value: 0,
    name: g_t('public.active')
  },
  {
    value: 0,
    name: g_t('public.unActive')
  }
])

watch(
  () => props.deviceActiveRate,
  () => {
    setOptions()
  },
  { deep: true }
)

onMounted(_ => {
  useChartMixin({
    refChart,
    myChart,
    setOptions
  }).initChart()
})

const setOptions = theme => {
  dataOptions.value[0].value = !props.deviceActiveRate.activeNum
    ? null
    : parseInt(props.deviceActiveRate.activeNum)
  dataOptions.value[1].value = !props.deviceActiveRate.noActive
    ? null
    : parseInt(props.deviceActiveRate.noActive)
  dataOptions.value.forEach((dataItem, index) => {
    dataItem.itemStyle = {
      color: ['#6fba2c', '#ff6565'][index]
    }
  })
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: [
      {
        orient: 'horizontal',
        x: 'center',
        bottom: 10,
        textStyle: {
          color: theme === 'theme-white' ? '#666666' : '#d5e4f6'
        },
        icon: 'circle',
        itemWidth: 10,
        itemHeight: 10,
        data: []
      },
      {
        orient: 'horizontal',
        x: 'center',
        bottom: 0,
        textStyle: {
          color: theme === 'theme-white' ? '#666666' : '#d5e4f6'
        },
        icon: 'circle',
        itemWidth: 15,
        itemHeight: 10,
        data: [
          {
            name: g_t('public.active')
          },
          {
            name: g_t('public.unActive')
          }
        ]
      }
    ],
    series: [
      {
        type: 'pie',
        top: 5,
        radius: ['40%', '60%'],
        label: {
          formatter: '{b}：{c}\n\n',
          padding: [0, 0]
        },
        minAngle: 5,
        data: dataOptions.value
      }
    ]
  }
  myChart.value &&
    myChart.value.setOption &&
    myChart.value.setOption(option, true)
}
</script>
